package com.bosssoft.setp.handler;

import com.bosssoft.setp.constant.CommonConstant;
import com.bosssoft.setp.model.business.course.Course;
import com.bosssoft.setp.model.business.course.CourseDetail;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.core.exception.EruptApiErrorTip;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.service.EruptUserService;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程数据代理
 *
 * @author clt
 */
@Service
public class CourseDataProxy implements DataProxy<Course> {
    @Resource
    private EruptUserService eruptUserService;

    @Resource
    private EruptDao eruptDao;

    String sqlForParentCode = "SELECT code FROM setp_course_type WHERE id = ?";

    String sqlForMaxCode = "SELECT MAX(code) FROM setp_course WHERE course_type_id = ?";

    String sqlForCourseCode = "SELECT code FROM setp_course WHERE id = ?";

    /**
     * 添加前操作
     * @param course
     */
    @Override
    public void beforeAdd(Course course) {
        course.setCreateUser(eruptUserService.getCurrentEruptUser().getName());
        course.setUpdateUser(eruptUserService.getCurrentEruptUser().getName());
        course.setCreateTime(new Date());
        course.setUpdateTime(new Date());

        if(!course.isBusyworkUseful() || !course.isVerbalTrickUseful()){
            throw new EruptApiErrorTip("话术和模板不可同时为空");
        }

        //检查默认附件
        boolean hasExactlyOneDefault = course.getCourseDetails().stream()
                .filter(CourseDetail::isDefault)
                .collect(Collectors.toSet()).size() == 1;

        if (!hasExactlyOneDefault) {
            throw new EruptApiErrorTip("默认附件数量应为1");
        }

        //生成编号
        String code = null;
        String parentCode = eruptDao.getJdbcTemplate().queryForObject(sqlForParentCode.replace("?",course.getCourseTypeId().toString()),String.class);
            String maxCode = eruptDao.getJdbcTemplate().queryForObject(sqlForMaxCode.replace("?",course.getCourseTypeId().toString()),String.class);
            if(maxCode != null){
                maxCode = maxCode.substring(maxCode.lastIndexOf(CommonConstant.COMMA) + 1);
                code = parentCode + CommonConstant.COMMA + String.format("%03d",Integer.parseInt(maxCode) + 1);
            }else {
                code = parentCode + CommonConstant.COMMA + String.format("%03d", 1);
            }
            course.setCode(code);
    }

    /**
     * 更新前操作
     * @param course
     */
    @Override
    public void beforeUpdate(Course course) {
        //检查默认附件
        boolean hasExactlyOneDefault = course.getCourseDetails().stream()
                .filter(CourseDetail::isDefault)
                .collect(Collectors.toSet()).size() == 1;

        if (!hasExactlyOneDefault) {
            throw new EruptApiErrorTip("默认附件数量应为1");
        }

        //检查编号
        String parentCode = eruptDao.getJdbcTemplate().queryForObject(sqlForParentCode.replace("?",course.getCourseTypeId().toString()),String.class);

        boolean isPrefix = course.getCode().startsWith(parentCode);
        if(!isPrefix){
            throw new EruptApiErrorTip("课程编码必须以课程类别编码开头");
        }

        //更新编号
        String code =  eruptDao.getJdbcTemplate().queryForObject(sqlForCourseCode.replace("?",course.getId().toString()),String.class);
        if (code == null){
            throw new EruptApiErrorTip("课程编码问题，请联系管理员处理");
        }

        if(!code.equals(course.getCode())){
            List<Map<String, Object>> results = eruptDao.getJdbcTemplate().queryForList(
                    "SELECT id, code FROM setp_course WHERE course_type_id = ? AND code >= ?",
                    course.getCourseTypeId(),
                    course.getCode()
            );

            Map<Object, String> courses = new HashMap<>();
            for (Map<String, Object> row : results) {
                courses.put(row.get("id"), (String) row.get("code"));
            }

            for (Map.Entry<Object, String> entry : courses.entrySet()) {
                Object key = entry.getKey();
                String value = entry.getValue();
                String oldCode = value;
                String lastPart = oldCode.substring(oldCode.lastIndexOf(CommonConstant.COMMA) + 1);
                String newCode = parentCode + CommonConstant.COMMA + String.format("%03d", Integer.parseInt(lastPart) + 1);
                eruptDao.getJdbcTemplate().update("UPDATE setp_course SET code = ? WHERE id = ?", newCode, key);
            }
        }
    }

    @Override
    public void afterDelete(Course course) {
        /**
         * 删除掉课程选择表中的相关课程
         */
        String sql = "DELETE FROM setp_course_select WHERE course_id =?";
        eruptDao.getJdbcTemplate().update(sql, course.getId());
    }

    @Override
    public void afterUpdate(Course course) {
        /**
         * 更新课程选择表中的信息
         */
        String sql = "UPDATE setp_course_select SET name =? , parent_id =? WHERE course_id = ?";
        String sql2 = "SELECT id FROM setp_course_select WHERE course_type_id = ? ";
        Long matchId = eruptDao.getJdbcTemplate().queryForObject(
                sql2, Long.class, course.getCourseTypeId());
        int rowsAffected = eruptDao.getJdbcTemplate().update(sql, course.getName(), matchId,course.getId());
    }


    @Override
    public void afterAdd(Course course) {
        for (CourseDetail detail : course.getCourseDetails()){
            eruptDao.getJdbcTemplate().update("UPDATE setp_course_detail SET course_id = ? WHERE id = ?", new Object[]{course.getId(), detail.getId()});
        }

        /**
         * 把课程添加到课程选择表中
         */
        String sql = "INSERT INTO setp_course_select (name,is_course,parent_id,course_id) VALUES (?, ?, ?,?)";

        String sql2 = "SELECT id FROM setp_course_select WHERE course_type_id = ? ";
        Long matchId = eruptDao.getJdbcTemplate().queryForObject(
                sql2, Long.class, course.getCourseTypeId());
        int rowsAffected = eruptDao.getJdbcTemplate().update(sql, course.getName(),true,matchId ,course.getId()  );

    }
}